package com.huadao.cart_ccs.main;

import android.app.Application;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;

import com.cart.event.SerialPortEvent;
import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.common.Constants;
import com.huadao.cart_ccs.common.CrashHandler;
import com.huadao.cart_ccs.common.FileUtils;
import com.huadao.cart_ccs.common.RockToast;
import com.huadao.cart_ccs.data.bean.DeviceInfo;
import com.huadao.cart_ccs.data.bean.Project;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;

public class CartApplication extends Application {
    private static CartApplication app;

    private byte[] agentNumber = {0x56, 0x01};//代理商编号
    //    private byte[] mac={(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};//MAC地址
    private byte[] mac = {(byte) 0xE0, (byte) 0xAA, (byte) 0xC8, (byte) 0xDE, 0x63, 0x52};//MAC地址

    private String TAG = "CartApplication";


    private DeviceInfo deviceInfo;
    private Project systemProject;
    private int referenceWeight;

    //保存项目信息
//    private Project project;
//    private ExperimentStage experimentStage;

    public static CartApplication getInstance() {
        return app;
    }


    /**
     * 主线程ID
     */
    public static int mMainThreadId = -1;
    /**
     * 主线程
     */
    public static Thread mMainThread;
    /**
     * 主线程Handler
     */
    public static Handler mMainThreadHandler;
    /**
     * 主线程Looper
     */
    public static Looper mMainLooper;

    public static long getMainThreadId() {
        return mMainThreadId;
    }

    public static Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        app = this;
        mMainThreadId = android.os.Process.myTid();
        mMainThread = Thread.currentThread();
        mMainThreadHandler = new Handler();
        mMainLooper = getMainLooper();

//        initIp();
        initFilePath();

        // 异常处理，不需要处理时注释掉这两句即可！
        CrashHandler crashHandler = CrashHandler.getInstance();
        // 注册crashHandler
        crashHandler.init(getApplicationContext());

        //初始化串口类
//        SerialPortSource.instance();

        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                throwable.printStackTrace();
            }
        });
//        smdtManager=SmdtManager.create(this);
//        if(smdtManager!=null) {
//            int b=smdtManager.smdtSetStatusBar(this, false);
//            if(b==0) {
//                Toast.makeText(CartApplication.getInstance(),"StatusBar hidden Succ",Toast.LENGTH_SHORT).show();
//            }else {
//                Toast.makeText(CartApplication.getInstance(),"StatusBar hidden Error",Toast.LENGTH_SHORT).show();
//            }
//        }else{
//            Toast.makeText(CartApplication.getInstance(),"smdtManager is null",Toast.LENGTH_SHORT).show();
//        }

//        configLog();
//        initDefaultParams();
//        projectDao = GreenDaoManager.getInstance().getNoCacheSession().getProjectDao();
//        experimentStageDao=GreenDaoManager.getInstance().getNoCacheSession().getExperimentStageDao();
    }

    //获取默认值
//    private void initDefaultParams(){
//        SharedPreferences sharedPreferences=getSharedPreferences(Constants.sp_environment, Context.MODE_PRIVATE);
//        if(sharedPreferences.contains(Constants.sp_environment_CO2)){
//            double CO2=Double.longBitsToDouble(sharedPreferences.getLong(Constants.sp_environment_CO2, 0));
//            ParamConsts.CO2=CO2;
//        }
//        if(sharedPreferences.contains(Constants.sp_environment_O2)){
//            double O2=Double.longBitsToDouble(sharedPreferences.getLong(Constants.sp_environment_O2, 0));
//            ParamConsts.O2=O2;
//        }
//        if(sharedPreferences.contains(Constants.sp_environment_temperature)){
//            double temperature=Double.longBitsToDouble(sharedPreferences.getLong(Constants.sp_environment_temperature, 0));
//            ParamConsts.temperature=temperature;
//        }
//        if(sharedPreferences.contains(Constants.sp_environment_initLiquidAmount)){
//            int initLiquidAmount=sharedPreferences.getInt(Constants.sp_environment_initLiquidAmount,0);
//            ParamConsts.initCultureLiquid=initLiquidAmount;
//        }
//    }

//    //初始化一个新项目
//    public void initProjectInfo() {
//        //删除之前项目的所有数据
//        GreenDaoManager.getInstance().clear();
//        Date now=new Date();
//        experimentStage=new ExperimentStage(1, getString(R.string.exp_prepare_active));
//        experimentStage.setStartDate(now);
//        project = new Project(null, now, null, false);
//        projectDao.insert(project);
//        experimentStage.setProjectId(project.getProjectId());
//        experimentStageDao.insert(experimentStage);
//
//        Constants.RawMessagefileName="project_"+project.getProjectId()+"_RawMessage.log";
//    }
//
//    //恢复一个项目
//    public void resumeProjectInfo(Project project) {
//        this.project = project;
//        List<ExperimentStage> experimentStageList=experimentStageDao.queryBuilder().where(ExperimentStageDao.Properties.ProjectId.eq(project.getProjectId())).orderDesc(ExperimentStageDao.Properties.StartDate).limit(1).list();
//        if(experimentStageList!=null&&experimentStageList.size()>0){
//            this.experimentStage=experimentStageList.get(0);
//        }
//        Constants.RawMessagefileName="project_"+project.getProjectId()+"_RawMessage.log";
//    }
//
//    //重新开始一个新项目
//    public void resetProjectInfo() {
//        Date now=new Date();
//        experimentStage=new ExperimentStage(1, getString(R.string.exp_prepare_active));
//        experimentStage.setStartDate(now);
//        project = new Project(null, new Date(), null, false);
//        projectDao.insert(project);
//        experimentStage.setProjectId(project.getProjectId());
//        experimentStageDao.insert(experimentStage);
//        Constants.RawMessagefileName="project_"+project.getProjectId()+"_RawMessage.log";
//    }



    private void initFilePath() {
        String filePath = FileUtils.getFilePath(this);
        Constants.CrashFilePath = filePath + Constants.CrashFilePath;
        Constants.CellImageFilePath = filePath + Constants.CellImageFilePath;
        Constants.logDir = filePath + Constants.logDir;
    }

    private void initIp() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.SharedPreferences_name, MODE_PRIVATE);
        String ip = sharedPreferences.getString("ip", "192.168.1.100");
        int port = sharedPreferences.getInt("port", 50000);
        Constants.HOST = ip;
        Constants.TCP_PORT = port;
    }

    public void changeIP(String ip) {
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.SharedPreferences_name, MODE_PRIVATE);
        sharedPreferences.edit().putString("ip", ip).commit();
        Constants.HOST = ip;
    }

    public DeviceInfo getDeviceInfo() {
        return deviceInfo;
    }

    public void setDeviceInfo(DeviceInfo deviceInfo) {
        this.deviceInfo = deviceInfo;
    }

    //    public ExperimentStage moveToStage(ExperimentStage currentStage) {
//        Date now=new Date();
//        //先记录旧的实验阶段
//        experimentStage.setEndDate(now);
//        experimentStageDao.update(experimentStage);
//        //再设置新的当前的阶段
//        currentStage.setStartDate(now);
//        //记录新的当前的阶段
//        experimentStageDao.insert(currentStage);
//        experimentStage=currentStage;
//        return experimentStage;
////        this.currentStage = currentStage;
//    }
//




    public byte[] getAgentNumber() {
        return agentNumber;
    }

    public void setAgentNumber(byte[] agentNumber) {
        this.agentNumber = agentNumber;
    }

    public byte[] getMac() {
        return mac;
    }

    public void setMac(byte[] mac) {
        this.mac = mac;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SerialPortEvent event) {
        if (event.isIsConnected()) {
            RockToast.showToastSafe(R.string.serial_port_connect_succ);
        } else {
            RockToast.showToastSafe(R.string.serial_port_connect_fail);
        }
    }

    public void setSystemProject(Project project) {
        this.systemProject = project;
    }

    public Project getSystemProject() {
        return systemProject;
    }

    public String getSystemProjectId() {
        if (systemProject == null) {
            return "";
        } else {
            return systemProject.getId();
        }
    }

    public String getSystemProjectIdentifier() {
        if(systemProject==null){
            return "";
        }
        return systemProject.getIdentifier();
    }

    public String getDevId() {
        if (deviceInfo != null) {
            return deviceInfo.getId();
        } else {
            return "";
        }
    }

    //获取生产人员的名字
    public String getOperator() {
        if(systemProject==null){
            return "";
        }else {
            return systemProject.getProdUser1Name();
        }
    }

    public void setReferenceWeight(double referenceWeight) {
        this.referenceWeight= (int) referenceWeight;
    }

    public int getReferenceWeight() {
        return referenceWeight;
    }

    public boolean isProjectStarted() {
        if(systemProject!=null&&systemProject.getStartTime()!=null){
            return true;
        }else {
            return false;
        }
    }
}
